<template>
    <div class="container">
        <!-- 背景 -->
        <div class="bg" :style="{ height: statusBarHeight + 180 + 'px' }"></div>
        <!-- 顶部状态栏 -->
        <div class="statusBar" :style="{ height: statusBarHeight + 'px' }"></div>
        <!-- 顶部导航栏 -->
        <div class="navBar" :style="{ height: 88 + 'rpx' }">
            <img :src="imgs.back" @click="back" />
            订单详情
        </div>
        <div class="title">支付信息</div>
        <div class="card">
            <div class="price">¥ {{ info.amount || "-" }}</div>
            <div class="info">
                <div class="item">
                    <div class="label">订单编号：</div>
                    <div class="value">{{ info.orderNo }}</div>
                </div>
                <div class="item">
                    <div class="label">停车场：</div>
                    <div class="value">{{ info.parkingLot }}</div>
                </div>
                <div class="item">
                    <div class="label">车牌号：</div>
                    <div class="value">{{ info.plateNumber }}</div>
                </div>
                <div class="item">
                    <div class="label">进场时间：</div>
                    <div class="value">{{ info.calStartTime }}</div>
                </div>
                <div class="item">
                    <div class="label">出场时间：</div>
                    <div class="value">{{ info.billingTime }}</div>
                </div>
                <div class="item">
                    <div class="label">停车时长：</div>
                    <div class="value">{{ info.chargedDurationSec }}</div>
                </div>
            </div>
        </div>
        <div v-if="info.orderNo" class="btn" @click="pay">立即支付</div>
    </div>
</template>
<script>
import { getOrderDetailByCarNumberAPI, getOrderDetailAPI, createDadaOrderAPI } from "../api/api";

const app = getApp();

const getQueryString = (url, key) => {
    let urlArr = url.split("?");
    if (!urlArr[1]) return "";
    var theRequest = {};
    var strs = urlArr[1].split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
    }
    return theRequest[key] == null ? "" : theRequest[key];
};
export default {
    data() {
        return {
            imgs: app.globalData.imgs,
            statusBarHeight: "",
            info: {},

            temp_token: "",
            openid: "",

            // 通过扫码参数获取
            inids: "",
            kind: "",
            identifier: "",
            gate: "",

            // 车牌号查询订单
            carNumber: "",

            pagesLength: 1,
        };
    },
    onShareAppMessage() {},
    onLoad(options) {
        console.log("options", options);
        this.pagesLength = getCurrentPages().length;

        // 获取顶部安全区域
        wx.getSystemInfo({
            success: (res) => {
                this.statusBarHeight = res.statusBarHeight;
            },
        });

        let { q, i, k, d, g, carNumber } = options;
        if (q) {
            let u = decodeURIComponent(q);
            this.inids = getQueryString(u, "d");
            this.kind = getQueryString(u, "k");
            this.identifier = getQueryString(u, "i");
            this.gate = getQueryString(u, "g");
        } else {
            this.inids = d;
            this.kind = k;
            this.identifier = i;
            this.gate = g;
            this.carNumber = carNumber;
        }
    },
    onShow() {
        // 获取临时token
        wx.showLoading({
            title: "加载中...",
        });
        app.getTempToken()
            .then((res) => {
                this.openid = res.openId;
                this.temp_token = res.token;
                wx.hideLoading();

                // 车牌号查询
                if (this.carNumber) {
                    this.getOrderDetailByCarNumber();
                }
                // 动态码查询
                else {
                    this.getOrderDetail();
                }
            })
            .catch((err) => {
                wx.hideLoading();
            });
    },
    methods: {
        back() {
            if (this.pagesLength > 1) {
                uni.navigateBack();
            } else {
                uni.switchTab({ url: "/pages/index" });
            }
        },
        // 根据车牌号查询订单详情
        getOrderDetailByCarNumber() {
            wx.showLoading({
                title: "查询中...",
            });
            getOrderDetailByCarNumberAPI({
                plate_number: this.carNumber,
                token: this.temp_token,
            })
                .then((res) => {
                    this.info = res;
                    wx.hideLoading();
                })
                .catch((err) => {
                    if (err === "未查询到订单" || err === "参数错误") {
                        setTimeout(() => {
                            uni.switchTab({
                                url: "/pages/index",
                            });
                        }, 2500);
                    }
                });
        },
        // 查询订单详情
        getOrderDetail() {
            wx.showLoading({
                title: "查询中...",
            });
            getOrderDetailAPI({
                inids: this.inids,
                kind: this.kind,
                identifier: this.identifier,
                gate: this.gate,
                token: this.temp_token,
            })
                .then((res) => {
                    this.info = res;
                    wx.hideLoading();
                })
                .catch((err) => {
                    if (err === "未查询到订单" || err === "参数错误") {
                        setTimeout(() => {
                            uni.switchTab({
                                url: "/pages/index",
                            });
                        }, 2500);
                    }
                });
        },
        // 拉起支付
        pay() {
            let dada_token = wx.getStorageSync("dada_token");
            createDadaOrderAPI(
                {
                    orderNo: this.info.orderNo,
                    amount: this.info.amountCent,
                    inid: this.info.inid,
                    identifier: this.info.identifier,
                    openid: this.openid,
                    token: dada_token || this.temp_token,
                    type: dada_token ? 2 : 1,
                    // amount: 1,
                    // identifier: "1716868376",
                    // inid: "fa24069719510hmgevqyr7lc",
                    // openid: "o1iXC5AUo8EqRF2jiFqgAcbCWUSs",
                    // orderNo: "20240621151257735268",
                    // token: "zbY4VvvVXYZQoeGDmMMg5w6F5zYGrP4bkUqwVRpn1SigPjV0M8Q9Zgc4pPBkBQWVw803QcPtYgS+xxHyg1xf0g==",
                    // type: 1,
                },
                (err) => {
                    if ((err && err.code === 411) || err.code === 413) {
                        // 411短期token过期 413订单过期
                        wx.showToast({
                            title: `订单超时，请在页面自动刷新后重试`,
                            icon: "none",
                        });
                        setTimeout(() => {
                            const pages = getCurrentPages();
                            const page = pages[pages.length - 1];
                            uni.redirectTo({
                                url: decodeURIComponent(page.$page.fullPath),
                            });
                        }, 1500);
                    } else {
                        wx.showToast({
                            title: err ? err.msg : "未知错误",
                            icon: "none",
                        });
                    }
                    return Promise.reject(err);
                }
            ).then((res) => {
                // 小程序支付
                wx.requestPayment({
                    timeStamp: res.timeStamp,
                    nonceStr: res.nonceStr,
                    package: res.package,
                    signType: res.signType,
                    paySign: res.paySign,
                    success: (res) => {
                        wx.showToast({
                            title: "订单支付成功",
                        });
                        setTimeout(() => {
                            uni.switchTab({ url: "/pages/mine" });
                        }, 1500);
                    },
                    fail: (err) => {
                        this.flag = false;
                        wx.hideLoading();
                        console.log("支付失败", err);
                    },
                });
            });
        },
    },
};
</script>
<style scoped lang="scss">
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    .bg {
        position: absolute;
        top: 0;
        width: 100%;
        background-image: linear-gradient(135deg, #4bd1a0, #18a86b);
    }
    .statusBar {
        position: relative;
        z-index: 2;
        width: 100%;
    }
    // .navBar {
    //     position: relative;
    //     z-index: 2;
    //     width: 100%;
    //     font-size: 30rpx;
    //     line-height: 1;
    //     display: flex;
    //     align-items: center;
    //     justify-content: center;
    //     color: #fff;
    // }

    .navBar {
        position: relative;
        z-index: 2;
        width: 100%;
        font-size: 30rpx;
        line-height: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        img {
            position: absolute;
            top: 19rpx;
            left: 20rpx;
            width: 50rpx;
            height: 50rpx;
        }
    }
    .title {
        font-size: 36rpx;
        line-height: 1;
        margin-top: 90rpx;
        margin-bottom: 32rpx;
        margin-left: 32rpx;
        align-self: flex-start;
        position: relative;
        z-index: 2;
        color: #fff;
        font-weight: bold;
    }
    .card {
        width: 686rpx;
        border-radius: 24rpx;
        background-color: #f8f8f8;
        position: relative;
        z-index: 2;
        .price {
            color: #ef562b;
            font-size: 60rpx;
            line-height: 1;
            margin: 55rpx 0;
            text-align: center;
            text-align: center;
        }
        .info {
            margin: 0rpx 20rpx;
            padding: 10rpx 0;
            border-top: 3rpx dashed #cccccc;
            .item {
                margin: 40rpx 0rpx;
                display: flex;
                color: #323232;
                font-size: 30rpx;
                line-height: 1;
                .label {
                    flex: none;
                    width: 180rpx;
                    margin-left: 25rpx;
                }
                .value {
                    margin-right: 25rpx;
                    flex: auto;
                    text-align: right;
                }
            }
        }
    }
    .btn {
        margin-top: 100rpx;
        width: 686rpx;
        height: 96rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 45rpx;
        color: #fff;
        font-size: 30rpx;
        background-color: #28c445;
    }
}
</style>
